<?php

namespace app\models;

use app\components\Api\UserSystemInfo;
use app\components\Fun;
use app\components\API;
use app\models\Error;
use app\models\user\IdentificationList;
use yii\base\Exception;
use app\components\WebUser;
use app\components\Html;
use Yii;

class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface {


    const defaultHead = '/h5/images/toux01.png';
    /**
     * 默认头像
     */
    const defaultAvatar = 'public/defaultavatar.jpg';

    //'http://p3.music.126.net/bTIoFKFaE1-JQpgN3OynGg==/1986817511391283.jpg';


    public $identityClass = 'app\models\User';

    /**
     * 管理员类型
     */
    const role_type_admin = 1;

    /**
     * 普通用户
     */
    const role_type_common = 0;

    /**
     * 网站原始用户
     */
    const bindtype_yuanshi = 0;

    /**
     * 微信登录用户
     */
    const bindtype_weixin = 6;

    /**
     * 角色类型
     */
    public static function role_type_array() {
        return [
            self::role_type_admin => '管理员',
            self::role_type_common => '普通用户'
        ];
    }

    /**
     * 绑定类型
     */
    public static function bindtype_array($type = 'all') {
        $arr = [
            self::bindtype_yuanshi => '原始',
            self::bindtype_weixin => '微信'
        ];
        if ($type === 'all') {
            return $arr;
        }
        return $arr[$type];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'username' => '用户名',
            'id' => 'ID',
            'role_type' => '角色类型',
            'bindtype' => '绑定类型',
            'time' => '注册时间',
            'regtime' => '注册时间',
            'open_id' => 'open_id',
            "introducer"=>'介绍人',
            'type'=>'用户类型'
        ];
    }

    public static function tableName() {
        //数据库表名修改user为admintbl_users  tbl_users '{{%bizhi}}';
        return '{{%users}}';
    }

    /**
     * 修改密码
     */
    public function upPassword($password) {
        $this->password = User::toPassword($password);
        $this->password_time = time();
        $this->update();
    }

    /**
     * 获取用户名
     */
    public static function OpenidToName($open_id) {
        $model = User::find()->where('open_id LIKE :open_id AND bindtype LIKE :bindtype',
                [':open_id' => $open_id,
            ':bindtype'=>self::bindtype_Ggame])->select('username')->one();
        if ($model !== null) {
            return $model->username;
        } else {
            return '';
        }
    }

    public static function toPassword($word) {
        return md5(base64_encode($word));
    }

    static $_identity = null;

    public static function findIdentity($id) {


        if (static::$_identity === null) {
            static::$_identity = static::findOne($id);
        }
        return static::$_identity;
    }

    public static function findIdentityByAccessToken($token, $type = null) {
        //  exit('48');
        return static::findOne(['access_token' => $token]);
    }

    public static function findByUsername($username) {
        //  exit('55');
        //username修改为name
        $user = static::findOne(['username' => $username]);
        return $user;
    }

    public static function findById($id) {
        $user = static::findOne(['id' => $id]);
        return $user;
    }

    /**
     * 返回用户的某些属性
     */
    public static function findByIdSel($id, $select) {
        return static::find()->where(['id' => $id])->select($select)->one();
    }

    /**
     * @inheritdoc
     */
    public function getId() {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey() {
        // return 'ffd';

        if ($this->authKey === null) {
            $this->authKey = time();
            $this->update();
        }
        return $this->authKey;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey) {


        return $this->authKey == $authKey;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password) {
        //    var_dump(User::toPassword($password));exit;
        return $this->password === User::toPassword($password);
    }

    /**
     * 判断是否为管理员权限
     */
    public function isAdmin() {
        if ($this->role_type === self::role_type_admin) {
            return true;
        } else {
            return false;
        }
    }

    public function is_bd($userJson) {
        //  print_r($userJson);exit;

        $user = User::find()->where([
                    'open_id' => $userJson['uid'],
                    'bindtype' => $userJson['bind_type']
                ])->one();
        if ($user) {
            $up = false;
            if ($user->username != $userJson['username']) {
                $user->username = $userJson['username'];
                $up = true;
            }
            if ($user->avatar != $userJson['avatar']) {
                $user->avatar = $userJson['avatar'];
                $up = true;
            }
            if ($up) {
                $user->update();
            }
            return $user;
        } else {
            return $this->bind($userJson);
        }
    }

    /**
     * 绑定新用户
     */
    public function bind($user_data) {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $info = $this->bindNewUser($user_data);

            $transaction->commit();
            return $info;
        } catch (Exception $ex) {
            $transaction->rollBack(); ///回滚
            $msg = $ex->getMessage();
            Fun::showmsg($msg);
        }
    }

    /**
     * 添加新用户
     * 如果成功返回用户id,如果失败抛出异常
     */
    private function bindNewUser($user_data) {
        $u = new User;
        $u->open_id = Html::encode($user_data['uid']);
        $u->username = Html::encode($user_data['username']);
        $u->bindtype = Html::encode($user_data['bind_type']);
        $u->avatar = Html::encode($user_data['avatar']);
        $u->role_type = User::role_type_common;
        $u->time = time();
        if(isset($user_data['logintype'])){
            $u->logintype=$user_data['logintype'];
        }
        if (!empty($user_data['regtime'])) {
            $u->regtime = (int) ($user_data['regtime'] / 1000);
        }
        if ($u->save()) {
            return $u;
        } else {
            throw new Exception('添加新用户失败');
        }
    }

    public function updata($user_data) {
        $u = self::findById($user_data['uid']);
        if ($u === null) {
            Error::addmsg('更新用户信息失败');
            return false;
        }
        /**
         * 检查数据是否完整
         */
        if (!isset($user_data['uid'], $user_data['initTime'])) {
            ////如果不完整,则记录一下错误
            Error::addmsg('更新失败,参数缺失:' . print_r($user_data, true));
            return false;
        }
        /*
          ////先检查用户的安装时间是否为0,如果为0则没有必要更新
          if($user_data['initTime']!=0){
          Userziliao::setSetupAppTime($user_data['uid'], $user_data['initTime']);
          }elseif($user_data['bind_type']==user::bind_type_js){
          ////如果为0,再次判断,是通过什么方式登录的,如果是app,再次检查
          Userziliao::setSetupAppTime($user_data['uid'],  Userziliao::apptime_SetupApp);
          }
         */
        if ($u->avatar == $user_data['avatar']) {
            return true;
        }
        $u->avatar = Html::encode($user_data['avatar']);
        if ($u->update()) {
            return true;
        } else {
            API::$errormsg_array = $u->getErrors();
            //    API::$errormsg=API::get_errorstr();
            API::$errormsg = '请稍候再试';
            Error::addmsg('更新用户信息失败:' . API::tostr($u->getErrors()));
            return false;
        }
    }

    /**
     * 返回指定id的头像
     */
    public static function getAvatarId($id) {

        $model = self::find()->where(['id' => $id])->select('avatar')->one();
        if ($model === null || empty($model->avatar)) {
            return \app\components\Lcms::getWeb(). self::defaultAvatar;
        } else {
            return $model->avatar;
        }
    }

    /**
     * 返回头像
     */
    public function getAvatar($ty = WebUser::AvatarMin) {
        if (empty($this->avatar)) {
            $this->avatar = self::defaultAvatar;
        }
        $url = $this->avatar;
        if ($ty === WebUser::AvatarMin) {
            $url.='?param=60y60';
        }
        return $url;
    }

    /**
     * 返回以用户头像和名字
     */
    public static function getnameAvatar($uid) {

        $user = self::findById($uid);

        if ($user === null) {
            return $uid;
        }
        if (empty($user->avatar)) {
            $user->avatar = self::defaultAvatar;
        } else {
            // $user->avatar.='?param=64y64';
        }
        // return "<img src='{$user->avatar}' class='avatar' /><span class='username'>{$user->username}</span>";
        $user->username = \app\components\Html::encode($user->username);
        $ustr = $user->username;
        $user->avatar = \app\components\Html::encode($user->avatar);
        return "<div style=\" background-image: url({$user->avatar});background-size: 100% 100%;\" class='avatar' ></div><a href='" .
                \yii\helpers\Url::to(['/admin/view/userlist', 'id' => $user->id])
                . "' target='_blank'><span class='username'>{$ustr}</span></a>";
    }

    public function login(){
        $token=IdentificationList::createIdentification($this->getId());
        $cookies = Yii::$app->response->cookies;
        // 在要发送的响应中添加一个新的cookie
        $cookies->add(new \yii\web\Cookie([
            'name' => 'token',
            'value' => $token,
        ]));
       return $token;///Yii::$app->user->login($this, 3600*24);
    }

}
